package cn.iocoder.yudao.module.pay.channel.service;

import cn.iocoder.yudao.framework.business.basic.dao.query.CoreLambdaQueryWrapper;
import cn.iocoder.yudao.framework.business.basic.dao.query.CoreQueryWrapper;
import cn.iocoder.yudao.framework.business.basic.pojo.dto.SimpleQueryDTO;
import cn.iocoder.yudao.framework.business.basic.service.impl.BaseService;
import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.pay.channel.dal.dataobject.PayChannelDO;
import cn.iocoder.yudao.module.pay.channel.dal.mysql.PayChannelMapper;
import cn.iocoder.yudao.module.pay.channel.vo.PayChannelSaveDTO;
import cn.iocoder.yudao.module.pay.channel.vo.PayChannelVO;
import cn.iocoder.yudao.module.pay.channel.vo.WxApiV3ConfigRespVO;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

/**
 * 支付渠道 Service 实现类
 *
 * @author 山野羡民
 */
@Service
@Validated
public class PayChannelServiceImpl extends BaseService<PayChannelDO, PayChannelVO, SimpleQueryDTO> implements PayChannelService {

    @Resource
    private PayChannelMapper payChannelMapper;

    @Nonnull
    @Override
    protected CoreQueryWrapper<PayChannelDO> buildQueryWrapper(SimpleQueryDTO param) {
        CoreQueryWrapper<PayChannelDO> wrapper = super.buildQueryWrapper(param);
        wrapper.orderByAsc("sort");
        wrapper.orderByDesc("id");
        return wrapper;
    }

    @Override
    public boolean update(PayChannelSaveDTO param, Long userId) {
        PayChannelDO entity = BeanUtils.toBean(param, PayChannelDO.class);
        int ret = payChannelMapper.updateById(entity);
        return SqlHelper.retBool(ret);
    }

    @Override
    protected PayChannelMapper getInjectedMapper() {
        return payChannelMapper;
    }

    @Override
    public PayChannelDO getDetailByCode(String code) {
        CoreLambdaQueryWrapper<PayChannelDO> wrapper = new CoreLambdaQueryWrapper<>();
        wrapper.eq(PayChannelDO::getCode, code);
        wrapper.orderByAsc(PayChannelDO::getSort);
        wrapper.orderByDesc(PayChannelDO::getId);
        wrapper.limitN(1);
        return payChannelMapper.selectOne(wrapper);
    }

    @Nonnull
    @Override
    public WxApiV3ConfigRespVO getWxApiV3Config(String code) {
        PayChannelDO entity = getDetailByCode(code);
        Assertions.notNull(entity, "微信 API v3 支付渠道配置不存在：" + code);
        WxApiV3ConfigRespVO configRespVO = JsonUtils.parseObject2(entity.getConfig(), WxApiV3ConfigRespVO.class);
        Assertions.notNull(configRespVO, "微信 API v3 支付渠道配置获取失败");
        return configRespVO;
    }

}
